/*!
 * Copyright (c) 2010 Jacob Essex
 *
 * Dual licenced under MIT or GPL 3 licneces
 * 
 * See the GPL3 or MIT files in the main directory for details
 */

require.def('db/sites', ['log/db', 'db'],
function(Log, Db){
    var Site = function(db, tbl, id){
        this.__proto__ = new Db.Row(this,db, tbl, id);

        this.Host    = '';
        this.ApiUrl  = '';
        this.SiteUrl = '';

        this.HasNotified = 0;  //has the notification been shown
        this.IsActive  = 0; //is there an active db for this site
    };
    return{

        /**
         * This db contains the list of sites known about, the list of possible sites et el. The assumption is that when the script
         * finds a new possible site, it checks the actual sites to see if it is known/exists etc.
         *
         * This is not responsible for keeping the list of sites upto date.
         *
         */
        SitesDb:function(db){
            var that = this;
            var tbl = new Db.TableDef('Sites', ['Host','ApiUrl', 'SiteUrl', 'HasNotified', 'IsActive']);


            this.ensureCreated = function(tx, funcs){
                var func = function(tx){
                    var sql = 'CREATE TABLE IF NOT EXISTS ' + tbl.name + ' ('
                            + 'Id integer, Host varchar (256), ApiUrl varchar(256),'
                            + 'SiteUrl varchar(256), HasNotified integer, IsActive integer,'
                            + 'PRIMARY KEY(Id)'
                            + ')';

                    tx.executeSql(
                        sql,
                        [],
                        funcs.success ? function(tx, rs){funcs.success(tx);} : function(){},
                        funcs.error ? function(tx, e){funcs.error(e.message);} : function(){}
                    );
                }

                if ( tx ){
                    func(tx);
                }else{
                    db.transaction(func);
                }

            }

            /**
             * Creates a new site
             *
             * Both the tx and the function callback are to maintain the style. Neither are technically needed.
             */
            this.createSite = function(tx, funcs){
                var s = new Site(db, tbl, Db.ROW_NOT_CREATED);
                Log.info('Created new site');
                funcs.success && funcs.success(tx, s);
            }

            /**
             * gets a site by the host name
             *
             * @param host the host name
             * @param success the callback function when successful.
             * @param notFound the callback when the host wasn't found
             * @param error the callback when an error occures
             */
            this.getByHost = function(tx, host, funcs){
                var func = function(tx){
                    tx.executeSql('SELECT * FROM '+tbl.name +' WHERE Host=?', [host],
                    function(tx, rs){
                        if ( rs.rows.length == 0 ){
                            Log.info('Cannot find site with host ' + host);
                            funcs.notFound && funcs.notFound();
                        }else if ( rs.rows.length > 1 ){
                            funcs.error && funcs.error('Unexpected number of results. Expceted 1 got '+rs.rows.length);
                        }else{
                            var row = rs.rows.item(0); //there should only be one
                            var id = row['Id'];
                            Log.info('Found site with Id ' + id);
                            var site = new Site(db, tbl, id); //generate new site
                            tbl.columns.forEach(function(k){ site[k] = row[k]; }); //transfer properties
                            funcs.success && funcs.success(tx, site);
                        }
                    },
                    function(tx, er){
                        funcs.error && funcs.error(er.message);
                    })
                }

                if ( tx ){
                    func(tx);
                }else{
                    db.transaction(func);
                }
                    
            }

            /**
             * tx must be a valid transaction
             *
             * todo
             */
            this.saveSite = function(tx, site, callbacks){
                that.getByHost(tx, site.Host, {
                    success:function(tx, s){
                        tbl.columns.forEach(function(k){ s[k] = site[k]; }); //transfer properties
                        s.save(tx, callbacks);
                    }
                });
            }

        }
    }
});
